package com.abigoni.ciaomondoandroid.bflows.activity;

import com.abigoni.ciaomondoandroid.R;
import com.abigoni.ciaomondoandroid.bflows.helper.MyDbHelper;
import com.abigoni.ciaomondoandroid.blogics.user.User;
import com.abigoni.ciaomondoandroid.blogics.user.UserService;

import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegisterActivity extends Activity{

	private SQLiteDatabase db;
	public MyDbHelper myDbHelper;
	public EditText nome;
	public EditText cognome;
	public EditText email;
	public EditText cdUser;
	public EditText pwd;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
	
		Button action    = null;
		
		nome       = (EditText) findViewById(R.id.edtNome);
		cognome    = (EditText) findViewById(R.id.edtCognome);
		email      = (EditText) findViewById(R.id.edtEmail);
		cdUser     = (EditText) findViewById(R.id.edtUsername);
		pwd        = (EditText) findViewById(R.id.edtPassword);
		action     = (Button)   findViewById(R.id.btnRegistrati);
		
		myDbHelper = new MyDbHelper(RegisterActivity.this);
		db         = this.myDbHelper.getWritableDatabase();
		
		action.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				UserService userService = new UserService(db);
				
				boolean result = userService.checkUsername(cdUser.getText().toString());
				if(result){
					//registrazione
					User user     = new User(nome.getText().toString(),cognome.getText().toString(),email.getText().toString(),
							cdUser.getText().toString(),pwd.getText().toString()); 
					long idInsert = userService.insertUser(user);
					
					if(idInsert > -1){
						Toast.makeText(RegisterActivity.this, "Registrazione avvenuta con successo!",Toast.LENGTH_LONG).show();
						
						Intent intent = new Intent(RegisterActivity.this,WelcomeActivity.class);
						intent.putExtra("user", "Benvenuto " +user.getNome());
						startActivity(intent);
						
					} else
						Toast.makeText(RegisterActivity.this, "Errore inserimento utente!",Toast.LENGTH_LONG).show();
					
				} else
					Toast.makeText(RegisterActivity.this, "Username gia' in uso!",Toast.LENGTH_LONG).show();
			}
		});
	}
}